<template>
  <div ref="chartDom" :style="styleObject" />
</template>

<script>
import * as echarts from "echarts";
import debounce from "lodash/debounce";

export default {
  name: "Chart",
  props: {
    option: {
      type: Object,
      default: () => {},
      required: true,
    },
    // 数字或百分比数字
    width: {
      type: String,
      default: "100%",
      required: false,
    },
    // 数字或百分比数字
    height: {
      type: String,
      default: "280px",
      required: false,
    },
  },
  computed: {
    styleObject: function () {
      return {
        width: this.isNumber(this.width) ? this.width + "px" : this.width,
        height: this.isNumber(this.height) ? this.height + "px" : this.height,
      };
    },
  },
  watch: {
    option(val) {
      this.chart.setOption(val);
    },
    // option: {
    //   handler(val) {
    //     this.chart.setOption(val);
    //   },
    //   deep: true, // 深度监听
    // },
  },
  created() {
    this.resize = debounce(this.resize, 300);
  },
  mounted() {
    this.renderChart();

    // 监听窗口变化
    window.addEventListener("resize", this.resize);

    // 监听点击事件
    this.chart.on("click", (params) => {
      // 控制台打印数据的名称
      console.log(params.name);
      this.$emit("click", params.name);
    });
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resize);
    // 销毁实例
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    isNumber(value) {
      return /(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/.test(
        value + ""
      );
    },
    resize() {
      // 自适应容器尺寸
      this.chart.resize();
    },
    renderChart() {
      // 基于准备好的dom，初始化echarts实例
      this.chart = echarts.init(this.$refs.chartDom);
      // 绘制图表
      this.chart.setOption(this.option);
    },
  },
};
</script>
